package com.gem.day16;

import java.io.*;
import java.net.Socket;

/**聊天室程序客户端*/
public class TalkClient {
	//主机
	private String host;
	//端口
	private int port;
	//通道[客户端套接字]
	private Socket socket;

	public TalkClient(String host, int port) {
		this.host = host;
		this.port = port;
	}

	//客户端连接服务端的方法
	public void connect() {
		try {
			//根据主机和端口号创建客户端套接字对象
			socket = new Socket(host, port);
			System.out.println("客户端已经连接成功...");
			beginTalk();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				//关闭客户端
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 开始聊天的方法
	 * @throws IOException 
	 */
	private void beginTalk() throws IOException {
		BufferedReader input = null;
		input = new BufferedReader(new InputStreamReader(System.in));
		PrintWriter pw = new PrintWriter(socket.getOutputStream());
		BufferedReader reply = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		//读取服务端的数据[启动一个线程负责]
		new Thread(() -> {
			String msg = null;
			try {
				while ((msg = reply.readLine()) != null) {
					System.out.println(msg);
				}
			} catch (IOException e) {
				System.out.println("打印线程退出...");
			}
		}).start();
		String line = null;
		System.out.print("你说: ");
		while (true) {
			//读取用户输入的信息
			line = input.readLine();
			//判断是否是退出指令
			if (line.equalsIgnoreCase("exit")) {
				//发送退出信息给服务器
				System.out.println(socket.getInetAddress().getHostAddress() + "下线了...");
				pw.println("[exit]");
				pw.flush();
				break;
			}
			//写入到目标服务器
			pw.println(line);
			pw.flush();
		}
	}

	public static void main(String[] args) {
		if (args.length < 1) {
			System.err.println("请输入一个IP地址");
			return;
		}
		String host = args[0];
		new TalkClient(host, 8888).connect();
	}
}
